﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using System.IO;

namespace Sinacor.Infra.Tools.ErrorLogCollector.ServerApplication
{
    public partial class ServerMain : Sinacor.Infra.Tools.ErrorLogCollector.BaseMain
    {
        public ServerMain()
        {
            InitializeComponent();
            this.Text += " - Servidor";
        }

        protected override void Collect(DateTime from, DateTime to, string path)
        {
            bool serverEmpty = true;
            LogPackage serverPackage = null;
            XmlSerializer serializer = new XmlSerializer(typeof(LogPackage));

            this.ShowStatus("Coletando informações do servidor...");

            // Coletar log server
            ServerCollector serverCollector = new ServerCollector();
            serverPackage = serverCollector.Collect(from, to);

            if (serverPackage.Server.Logs.Count > 0)
                serverEmpty = false;

            this.ShowStatus("Gerando pacote...");

            // Salvar e zipar package
            if (!serverEmpty)
            {
                if (File.Exists(path))
                    File.Delete(path);

                using (MemoryStream stream = new MemoryStream())
                {
                    serializer.Serialize(stream, serverPackage);

                    stream.Position = 0;

                    using (Ionic.Zip.ZipFile zipFile = new Ionic.Zip.ZipFile(path))
                    {
                        zipFile.AddEntry("LogPackage.xml", "\\", stream);
                        zipFile.Save();
                    }
                }
            }

            this.ShowStatus(string.Empty);

            if (!serverEmpty)
                MessageBox.Show("Logs do servidor coletados com sucesso", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);

            else
                MessageBox.Show("Nenhum log encontrado no servidor para o período informado", "Informação", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
